package com.sentinel.demo02.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.sentinel.demo02.service.HelloService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
public class HelloController {
    @Autowired
    private HelloService helloService;

    @GetMapping("/hello")
    public String sayHi(String name) {
        log.info("luban-demo hello功能入参:{}",name);
        // 1.对资源的保护就是添加一个sentinel入口
        // 2.入口之后的代码看做要保护的资源
        Entry entry = null;
        String result;
        try {
            // 设置一个entry，对资源进行保护
            entry = SphU.entry("sayHi");
            result = helloService.sayHi(name);
        } catch (BlockException e) {
            // entry抛出了异常，说明被限流了，提供限流逻辑下的降级处理方案
            log.error("hello功能被sentinel限流了",e);
            return "被sentinel限流了";
        } finally {
            // 释放资源
            if (entry != null)
                entry.exit();
        }
        return result;
    }
}
